package models
/*********************************************************/
/********************本文档为数据库结构文档******************/
/*************ShareRemoteWareHouse的数据结构****************/
/*********************version:1.0*************************/
/****Copyright (c) 2014年 许剑华. All rights reserved******/
/*********************************************************/
import (
	"github.com/astaxie/beego/orm"
	"gopkg.in/mgo.v2/bson"
	"gopkg.in/mgo.v2"
	//"gopkg.in/mgo.v2/mgo"
	"time"
	"github.com/astaxie/beego"
	//."smart_home/lib"
	//m "smart_home/controllers/dataType"
	//"github.com/astaxie/beego/validation"
)

//存储与mysql中的，与分享相关的描述数据
type ShareRemote struct {
	Id          		int64			`orm:"unique;auto"`
	Factory    			string
	DeviceModel			string										//设备型号
	DeviceType			string										//设备类型
	Descript			string										//描述
	ObjectId					string                                     //遥控数据存储的位置
	User *User `orm:"rel(fk)"`
	ShareTime    	time.Time `orm:"type(datetime);auto_now_add" `
}
//存储与mongodb中的，与分享相关的遥控数据598516
type ShareRemoteWareHouse struct {
	ObjectId 				bson.ObjectId "_id"
//	RemoteName				string			`valid:"Required;AlphaDash"`
//	No						string			`valid:"Required;AlphaDash"`
//	Version					string			`valid:"Required;AlphaDash"`
//	DeviceType				int				`valid:"Required;Numeric"`
//	Descript				string			`valid:"Required;AlphaDash"`							//描述
//	SaveUrl					string                                     //遥控数据存储的位置
//	User    				int64           `valid:"Required;Numeric"`                             //上传用户的ID
//	ShareTime    			time.Time 		`orm:"type(datetime);auto_now_add" `
//	TimeScale			    int				`valid:"Required;Numeric"`						   //采样电平的宽度
//	IRFRQ					int				`valid:"Required;Numeric"`							//载波频率
//	One						string
//	Zero						string
//	S                       string
//	A                       string
//	B                       string
//	C                       string
//	D                       string
//	E                       string
//	BootCode    			string			`valid:"Required;AlphaDash"`							//遥控的开机码字
//	PoweroffCode			string			`valid:"Required;AlphaDash"`							//遥控的关机码字
//	AcCode					AcType
	StorageCode				string			`orm:"type(text)"`
}

//验证验证码
type RespSearchType	struct {
	RespCode				int
	Data					[]ShareRemote

}

//验证验证码
type DownSearchDataType	struct {
	RespCode				int
	Data					ShareRemoteWareHouse

}
//注册数据表
func init() {
	// 需要在init中注册定义的model
	orm.RegisterModel(new(ShareRemote))
}
//设置数据表的表名
func (u *ShareRemote) TableName() string {
	return "share_remote"
}

//func GetShareRemote(Factory string,DeviceModel string,DeviceType string)([]ShareRemote,int64,error){
//	o := orm.NewOrm()
//	var mShareRemote []ShareRemote
//	num,err := o.Raw("SELECT * FROM share_remote WHERE factory == ? or device_model == ? or descript", Factory,DeviceModel,DeviceType,Factory).QueryRows(&mShareRemote)
//
//	return mShareRemote,num,err
//}

//搜索用户分享的数据
//@param 	 SearchText    string            搜索数据的字符串
//@return   	 		 []ShareRemote      返回的空调数据的数组
//@return   	 		 int64              返回的数据的数量
//@return   	         error      返回的错误
func SearchShareRemote(SearchText string)([]ShareRemote,int64,error){
	o := orm.NewOrm()
	var mShareRemote []ShareRemote
	search_query := "SELECT * FROM share_remote WHERE factory like '%"+SearchText+"%' or device_model like '%"+SearchText+"%' or device_model like '%"+SearchText+"%' or descript like '%"+SearchText+"%'"
	//var result	[]ShareRemoteWareHouse
	num,err := o.Raw(search_query).QueryRows(&mShareRemote)
	if err != nil{
		return mShareRemote,0,err
	}
	if num == 0{
		mShareRemote = make([]ShareRemote, 1)
		return mShareRemote,num,err
	}
	return mShareRemote,num,err
}
//获取用户分享的数据
//@param 	 object_id    string            数据的id
//@return   	 		 []ShareRemote      返回的空调数据
//@return   	         error      返回的错误
func GetShareRemote(object_id string)(ShareRemoteWareHouse,error){
	//var result	ShareRemoteWareHouse
//	var result	[]ShareRemoteWareHouse
//	result = make([]ShareRemoteWareHouse,num)
//	for i:= int64(0);i < num;i++{
//		data,_ := GetMgoRemoteByID(mShareRemote[i].ObjectId)
//		result[i] = data
//	}
	data,err := GetMgoRemoteByID(object_id)
	return data,err
}
//向数据库加入用户分享的数据
//@param 	 data    	 *ShareRemote        用户要分享的数据的描述数据
//@param 	 userID    	 int64               上传用户的ID
//@param 	 remote    	 ShareRemoteWareHouse        用户要分享的遥控数据
//@return   	         error      返回的错误
func AddShareRemote(data *ShareRemote,userID int64,remote ShareRemoteWareHouse)(error){
	err_mgo := AddMgoRemote(&remote,userID)
	if err_mgo != nil{
		beego.Error("mongodb err")
		return err_mgo
	}
	o := orm.NewOrm()
	user ,err := GetUserById(userID)
	if err !=nil{
		return err
	}
	data.User = &user
	//byte ,_:= bson.NewObjectId().MarshalJSON()
	err = AddMgoRemote(&remote,user.Id)
	data.ObjectId =remote.ObjectId.ObjectIdHex()
	_, err = o.Insert(data)
	if err != nil{
		beego.Error("mongodb err",err)
		return err
	}
	return err
}
//获取匹配的空调遥控器数据
//@param 	 data    	 string         			 需要匹配的开机码
//@return 	       	     []ShareRemoteWareHouse      匹配到的遥控数据数组
//@return 	      	     int        				 匹配的数据数量
//@return   	         error      				 返回的错误
func MatchMgoAcRemote(code string)([]ShareRemoteWareHouse,int,error){
	var result []ShareRemoteWareHouse

	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		beego.Error("mongodb err")
		panic(err)
		return result,0,err
	}
	defer session.Close()
	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)

	c := session.DB("smart_home").C("RemoteWareHouse")
	err = c.Find(bson.M{"bootcode": code}).All(&result)

	if err != nil {
		return result,0,err
	}

	num := len(result)
	return result,num,err
}
//向遥控数据库加入遥控的数据
//@param 	 data    	 *ShareRemoteWareHouse        用户要分享的数据的描述数据
//@param 	 userID    	 int64               	      上传用户的ID
//@return   	         error      返回的错误
func AddMgoRemote(data *ShareRemoteWareHouse,userID int64)(error){
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		beego.Error("mongodb err")
		panic(err)
		return err
	}
	defer session.Close()
	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)
//	data.User = userID
	data.ObjectId = bson.NewObjectId()
	c := session.DB("smart_home").C("ShareRemoteWareHouse")
	err = c.Insert(data)
	if err != nil {
		beego.Error("mongodb err",err)
		return err
	}
	return err
}

//更新遥控数据库的遥控数据
//@param 	 ObjectId    	 string        遥控器数据的ID
//@param 	 data    	     ShareRemoteWareHouse               	   要存储的遥控器数据
//@return   	             error      返回的错误
func UpdateMgoRemote(ObjectId string,data ShareRemoteWareHouse)(error){
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		beego.Error("mongodb err")
		panic(err)
		return err
	}
	defer session.Close()
	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)

	c := session.DB("smart_home").C("ShareRemoteWareHouse")
	err = c.Update(bson.M{"_id": ObjectId}, data)

	if err != nil {
		beego.Error("mongodb err",err)
		return err
	}
	return err
}

//获取遥控数据库的遥控数据
//@param 	 ObjectId    	 string                                    遥控器数据的ID
//@return 	 data    	     ShareRemoteWareHouse               	   获取的遥控器数据
//@return   	             error      							   返回的错误
func GetMgoRemoteByID(objectId string)(ShareRemoteWareHouse, error){
	var result ShareRemoteWareHouse
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		beego.Error("mongodb err")
		panic(err)
		return result,err
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)

	c := session.DB("smart_home").C("ShareRemoteWareHouse")
	//mObjectId := new(bson.ObjectId)
	var o_Id	string
	o_Id = objectId
	object_Id := bson.ObjectIdHex(o_Id)

	err = c.FindId(object_Id).One(&result)

	if err != nil {
		beego.Error("mongodb err",err)
		return result,err
	}
	return result,err
}
